package tech.aistar.controller.mycat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.aistar.entity.mycat.CodeStatus;
import tech.aistar.entity.mycat.Result;
import tech.aistar.entity.mycat.ValidGroup3;
import tech.aistar.entity.personal.User;
import tech.aistar.entity.personal.UserInfo;
import tech.aistar.service.personal.IUserInfoService;
import tech.aistar.service.personal.IUserService;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:关于用户操作的C
 * @date 2019/9/23 0023
 */
@Controller
@RequestMapping("/user")
public class UserController {

    //控制层就是调用service层.

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserInfoService userInfoService;


    //异步检测用户名是否存在
    @GetMapping("/checkName")
    public @ResponseBody Result checkUser(User user) {
        User u = userService.findByName(user.getUsername());
        if (null == u) {
            return new Result(CodeStatus.OK, true, "用户名可用", u);
        }
        return new Result(CodeStatus.ERROR, false, "用户名不可用", u);
    }

    @RequestMapping("/registerAction")
    public String register(User user,HttpServletRequest request) {

        User u = userService.findByName(user.getUsername());
        if (null != u) {
            return "redirect:mycat/register";
        }
        //创建用户的时候应该同时创建一个用户信息表
        userService.save(user);
        System.out.println("user:" + user);
        //创建用户信息表
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar("http://py5ztkhmu.bkt.clouddn.com/19d10a67-5283-42ce-b851-ed8c6d2b5e66.png");
        userInfo.setNickname(user.getUsername());
        userInfoService.save(userInfo);

        request.getSession().setAttribute("user",user);
        request.getSession().setAttribute("userInfo",userInfo);
        return "redirect:/foster/index";
    }

    //跳转到登录界面
    @RequestMapping("/loginView")
    public String loginView() {
        return "personal/login";
    }

    //注册界面
    @RequestMapping("/registerView")
    public String registerview() {
        return "mycat/register";
    }

}
